package controllers

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
	"math/rand"
	"os"
	"path"
	"time"
	"wego/models"
)

type UploadController struct {
	BaseController
}

func (this *UploadController) GetAttach() {
	params := &models.AttachQueryParam{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, params)
	list, count := models.AttachList(params)
	result := models.ResultList{}
	result.List = list
	result.Count = count
	this.JsonResult(1, "操作成功", &result)
}

func (this *UploadController) MoveAttachToType() {
	params := &models.MoveAttachToTypeParam{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, params)
	_, err := models.MoveAttachToType(params)
	if err == nil {
		this.JsonResult(1, "操作成功", "")
	} else {
		this.JsonResult(0, "操作失败", "")
	}
}

func (this *UploadController) DelAttach() {
	params := &models.DelAttachParam{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, params)
	_, err := models.DelAttach(params)
	if err == nil {
		this.JsonResult(1, "操作成功", "")
	} else {
		this.JsonResult(0, "操作失败", "")
	}
}

func (this *UploadController) GetType() {
	list, count := models.AttachTypeList()
	result := models.ResultList{}
	result.List = list
	result.Count = count
	this.JsonResult(1, "操作成功", &result)
}

func (this *UploadController) SaveType() {
	params := &models.AttachType{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, params)
	id, err := models.SaveAttachType(params)
	if err == nil {
		params.Id = id
		this.JsonResult(1, "操作成功", params)
	} else {
		this.JsonResult(0, "操作失败", "")
	}
}

//删除分类
func (this *UploadController) DelType() {
	params := &models.AttachType{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, params)
	err := models.DelAttachType(params)
	if err == nil {
		this.JsonResult(1, "操作成功", "")
	} else {
		this.JsonResult(0, "操作失败", "")
	}
}

//本地上传
func (this *UploadController) DoUpload() {
	//这里type没有用，只是为了演示传值
	token := this.GetString("Authorization")
	if token != "" {
		typeId, _ := this.GetInt64("typeId", 0)

		f, h, err := this.GetFile("file")

		if err != nil {
			this.JsonResult(0, "上传失败", "")
		}
		ext := path.Ext(h.Filename)
		//验证后缀名是否符合要求
		var AllowExtMap map[string]bool = map[string]bool{
			".jpg":  true,
			".jpeg": true,
			".png":  true,
		}
		if _, ok := AllowExtMap[ext]; !ok {
			this.JsonResult(0, "后缀名不符合上传要求", "")
		}

		uploadDir := "static/upload/" + time.Now().Format("20060102/")
		err = os.MkdirAll(uploadDir, 777)
		if err != nil {
			this.JsonResult(0, "保存目录创建失败", "")
		}
		//构造文件名称
		rand.Seed(time.Now().UnixNano())
		randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000)
		hashName := md5.Sum([]byte(time.Now().Format("2006_01_02_15_04_05_") + randNum))

		fileName := fmt.Sprintf("%x", hashName) + ext
		fpath := uploadDir + fileName
		defer f.Close()

		// 保存位置在 static/upload, 没有文件夹要先创建
		err = this.SaveToFile("file", fpath)
		if err != nil {
			this.JsonResult(0, fmt.Sprintf("%v", err), "")
		}
		params := &models.Attach{}
		params.Type = typeId
		params.Name = h.Filename
		params.SaveType = 1
		params.Ext = ext
		params.Size = int(h.Size)
		params.Path = fpath
		_, err = models.SaveAttach(params)
		if err == nil {
			this.JsonResult(1, "上传成功", beego.AppConfig.String("domain")+fpath)
		} else {
			this.JsonResult(0, "上传失败", "")
		}

	}
}

//保存七牛文件key
func (this *UploadController) QiniuUpload() {
	data := models.QiniuUploadData{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, &data)
	if data.Key == "" {
		this.JsonResult(0, "参数错误", "")
	}
	params := models.Attach{
		Type:     data.Type,
		Name:     data.Key,
		QnKey:    data.Key,
		SaveType: 2,
	}
	params.Path = beego.AppConfig.String("qiniu::Domain") + data.Key
	_, err := models.SaveAttach(&params)
	if err == nil {
		this.JsonResult(1, "上传成功", params.Path)
	} else {
		this.JsonResult(0, "上传失败", "")
	}
}

//是否开启七牛上传
func (this *UploadController) GetQiniuToken() {
	status := beego.AppConfig.String("qiniu::Status")
	result := make(map[string]interface{})
	if status == "open" {
		AccessKey := beego.AppConfig.String("qiniu::AccessKey")
		SecretKey := beego.AppConfig.String("qiniu::SecretKey")
		Bucket := beego.AppConfig.String("qiniu::Bucket")
		Action := beego.AppConfig.String("qiniu::Action")
		Domain := beego.AppConfig.String("qiniu::Domain")
		putPolicy := storage.PutPolicy{
			Scope: Bucket,
		}
		putPolicy.Expires = 7200 //2小时有效期
		mac := qbox.NewMac(AccessKey, SecretKey)
		UpToken := putPolicy.UploadToken(mac)
		result["action"] = Action
		result["domain"] = Domain
		result["upToken"] = UpToken
		result["isQiNiu"] = 1
		this.JsonResult(1, "操作成功", &result)
	} else {
		result["isQiNiu"] = 0
		this.JsonResult(1, "操作成功", &result)
	}
}
